<template>
	<div>
		<div class="pageTitle boxFlex">
			我的消息
		</div>
		<div class="pageContent">
			<div class="messageBox flex" style="justify-content: space-between;">
				<messageList @clickMsgList="clickMsgList" ref="messageListBox"></messageList>
				<div class="webSoketBox">
					<div class="webSoketBoxHeader">{{ msgItemClickData.name }}</div>
					<div class="webSoketMessage" ref="webSoketMessage">
						<!-- <input type="text" v-model=""> -->
						<vue-scroll :ops="cops" ref="vuescroll" @handle-resize="handleResize" @handle-scroll="handleScroll" style="width:100%;height:100%;">
							<ul class="webSoketUl" ref="webSoketUl">
								<div class="iconLadingBox" v-show="contentIsLoading"><i class="el-icon-loading"></i></div>
								<div v-for="(item, index) in chattingRecords" :key="index">
									<li class="receiveBox flex" v-if="item.sendType == 1 && item.messageType == 0">
										<img :src="item.head" alt="" class="webSoketHeadImg">
										<div class="webSoketContent">
											<div class="receiveBoxName">{{ item.name }}</div>
											<div class="receiveBoxCont">{{ item.sendContent }}</div>
											<!-- <div class="receiveBoxCont">
												<img src="../../../../../assets/image/management/guo2.png" alt="" style="max-width: 28rem;">
											</div> -->
										</div>
									</li>
									<li class="webSokeTip" v-if="item.messageType == 1">{{ item.sendContent }}</li>
									<li class="sendBox flex" v-if="item.sendType == 0 && item.messageType == 0">
										<div class="webSoketContent">
											<div class="receiveBoxName">{{ item.name }}</div>
											<!-- 文本 -->
											<div class="sendBoxCont">{{ item.sendContent }}</div>
											<!-- 图片 -->
											<!-- <div class="sendBoxCont">
												<img src="../../../../../assets/image/management/guo2.png" alt="" style="max-width: 28rem;">
											</div> -->
										</div>
										<img :src="item.head" alt="" class="webSoketHeadImg">
									</li>
								</div>
							</ul>
						</vue-scroll>
					</div>
					<div class="webSoketInputBox">
						<div class="webSoketBoxIcon flex">
							<div class="flex funcImageBox">
								<img src="@/assets/image/addressList/tp.png" alt="" class="funcImage">
								<img src="@/assets/image/addressList/wj.png" alt="" class="funcImage">
								<img src="@/assets/image/addressList/gg.png" alt="" class="funcImage">
								<img src="@/assets/image/addressList/rc.png" alt="" class="funcImage">
							</div>
							<span>更多</span>
						</div>
						<!-- <div class="webSoketBoxinput" v-html="webSoketBoxinput" contenteditable="true" @keyup.enter.native="submit"></div> -->
						<!-- <div class="webSoketBoxinput" v-model="webSoketBoxinput" contenteditable="true" @keyup.13="submit(webSoketBoxinput)"></div> -->
						<!-- <textarea class="webSoketBoxinput" v-model="webSoketBoxinput" name="" id="" cols="30" rows="10" @keyup.13="submit()"></textarea> -->
						<textarea class="webSoketBoxinput" v-model="webSoketBoxinput" name="" id="" cols="30" rows="10"></textarea>
						<!-- <el-input type="textarea" :rows="2" placeholder="请输入内容" @keyup.enter.native="submit(webSoketBoxinput)" v-model="webSoketBoxinput"></el-input> -->
						<div class="webSoketBoxBtn">
							<el-popover placement="left" title="" width="200" trigger="manual" content="发送内容不能为空" v-model="isSendMessageContents">
								<el-button slot="reference" @click="submit(webSoketBoxinput)">发送</el-button>
							</el-popover>
							<!-- <el-button @click="submit(webSoketBoxinput)">发送</el-button> -->
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	import messageList from './components/messageList.vue'
	export default {
		components: {
			messageList
		},
		data() {
			return {
				cops: {
					vuescroll: {},
					scrollPanel: {},
					rail: {
						keepShow: true
					},
					bar: {
						hoverStyle: true,
						onlyShowBarOnScroll: false, //是否只有滚动的时候才显示滚动条
						background: "#D6D8DD", //滚动条颜色
						opacity: 0.9, //滚动条透明度
						"overflow-x": "hidden"
					}
				},
				userInfo: '', // 用户个人信息
				userId: '',
				webSoketBoxinput: '',
				chattingRecords: [], // 聊天记录
				// chatName: '' ,// 当前聊天对象名称
				msgItemClickData: '', // 聊天列表点击事件传递的当前点击对象数据
				isSendMessageContents: false, // 发送内容为空时的提示
				// chatKey: new Date().getTime(),
				pageNum: 1 ,// 请求页码
				// oldPageNum: 1,
				contentIsLoading: false,
				webSoketUlOffsetHeight: 0 ,// 动态滚动条高度
				chatTotalPageNum: 0 ,// 聊天记录总页数
				isSendContent: false // 判断是发送内容还是加载内容
			};
		},
		created() {
			this.$store.commit('set_myManagementNavIndex', 11)
		},
		mounted() {
			this.userInfo = this.$store.state.user.userInfo
			this.userId = this.userInfo.id
		},
		computed: {
			monitor () {
				return this.$store.state.addressList.socktNewMessage
			}
		},
		watch:{
			monitor(newData){
				// 监听收到新消息
				let data = {
					chatId: this.msgItemClickData.chatId,
					chatType: null,
					createDate: null,
					fromUserId: null,
					head: this.msgItemClickData.head,
					id: this.msgItemClickData.id,
					isReadCount: null,
					messageType: 0,
					name: this.msgItemClickData.name,
					sendContent: newData.data,
					sendType: 1,
					toUserId: null
				}
				// 想拿到的缓存数据添加新数据
				this.chattingRecords.push(data)
				// 将新组合的数据添加至缓存
				sessionStorage.setItem('chatContent', JSON.stringify(this.chattingRecords))
				// 设置滚动条位置到底部
				this.isSendContent = true
				// 更新列表数据
				this.$refs.messageListBox.getMsgList()
				// this.$refs.vuescroll.scrollTo({y: this.$refs.webSoketUl.offsetHeight,x: 0},0,"easeInQuad")
				this.$forceUpdate()
			},
			webSoketUlOffsetHeight(newData, oldData){
				this.$refs.vuescroll.scrollTo({y: (newData - oldData),x: 0},0,"easeInQuad")
				// console.log(newData, oldData)
			}
		},
		methods: {
			handleScroll(vertical, horizontal, nativeEvent) {
				// 判断滚动条是否到顶部
				if(vertical.scrollTop === 0 && this.pageNum < this.chatTotalPageNum){
					// console.log('滚动条到顶部')
					this.pageNum += 1
					this.getMsgList()
					// this.$refs.vuescroll.scrollTo({y: nativeEvent.height,x: 0},0,"easeInQuad")
				}
			},
			handleResize(vertical, horizontal, nativeEvent) {
				/**
				 * obj X和y的滚动距离
				 * 滚动速度
				 * 滚动动画
				 */
				if(this.pageNum === 1 || this.isSendContent){
					this.$refs.vuescroll.scrollTo({y: nativeEvent.height,x: 0},0,"easeInQuad")
					this.isSendContent = false
				}
			},
			submit(e) {
				// 发送聊天内容
				let reg = /\S/
				// console.log(this.msgItemClickData)
				if(!reg.test(this.webSoketBoxinput)){
					// 判断聊天内容是否为空
					// console.log('111111111111111')
					this.isSendMessageContents = true
					setTimeout(()=>{
						this.isSendMessageContents = false
					},3000)
					return
				} else {
					// console.log('222222222222222')
					this.isSendMessageContents = false
					// 请求发送消息接口
					this.$request.postForm(this.$api.sendMessage, {
						fromUserId: this.userId, // 发送者用户id
						toUserId: this.msgItemClickData.userId, // 接收者用户id
						chatType: this.msgItemClickData.chatType, // 消息类型：列表类型:0为个人，1为公司，2为部门
						message: this.webSoketBoxinput, // 消息体
						chatId: this.msgItemClickData.chatId // 聊天列表id
					}).then(res => {
						if (res.code == 200) {
							// 需要向缓存数据添加的数据对象
							let sendData = {
								chatId: "null",
								chatType: null,
								createDate: null,
								fromUserId: null,
								head: this.userInfo.head,
								id: this.msgItemClickData.id,
								isReadCount: null,
								messageType: 0,
								name: this.userInfo.name,
								sendContent: this.webSoketBoxinput,
								sendType: 0,
								toUserId: null
							}
							// 想拿到的缓存数据添加新数据
							this.chattingRecords.push(sendData)
							// 将新组合的数据添加至缓存
							sessionStorage.setItem('chatContent', JSON.stringify(this.chattingRecords))
							// 清空已发送的内容
							this.webSoketBoxinput = ''
							// 设置滚动条位置到底部
							this.isSendContent = true
							// 更新列表数据
							this.$refs.messageListBox.getMsgList()
							// this.chattingRecords = sessionStorage.setItem('chatContent', JSON.stringify(this.chattingRecords))
							// this.$refs.vuescroll.scrollTo({y: this.$refs.webSoketUl.offsetHeight,x: 0},0,"easeInQuad")
							this.$forceUpdate()
						}
					}).catch(err=>{
						// this.$message.error('发送失败')
					})
				}
			},
			clickMsgList(item) {
				// 列表点击事件
				this.msgItemClickData = item
				
				this.pageNum = 1
				this.getMsgList()
			},
			getMsgList() {
				// console.log(this.msgItemClickData)
				if(this.msgItemClickData.isNew || !this.msgItemClickData.chatId){
					return
				}
				this.contentIsLoading = true
				this.$request.postForm(this.$api.findMessageIdQuery, {
					messageId: this.msgItemClickData.chatId,
					userId: this.userId,
					chatType: this.msgItemClickData.chatType,
					page: this.pageNum,
					pageSize: 10
				}).then(res => {
					if (res.code == '200') {
						// 清空聊天内容
						// this.chattingRecords = []
						this.chatTotalPageNum = res.data.totalPage // 聊天记录总页数
						// 消息数组翻转后拼接到原有聊天记录前面
						// console.log(res.data.items)
						if(this.pageNum == 1){
							this.chattingRecords = res.data.items.reverse()
						} else {
							this.chattingRecords = res.data.items.reverse().concat(this.chattingRecords)
						}
						// 存入缓存
						sessionStorage.setItem('chatContent', JSON.stringify(this.chattingRecords))
						// 赋值聊天记录容器的总高度
						setTimeout(()=>{
							this.webSoketUlOffsetHeight = this.$refs.webSoketUl.offsetHeight
							// console.log(this.$refs.webSoketUl.offsetHeight)
						},100)
						// this.oldPageNum = this.pageNum
						this.contentIsLoading = false
					} else {
						this.contentIsLoading = false
					}
				}).catch(err=>{
					this.contentIsLoading = false
				})
			}
		},
		beforeDestroy() {
			// 实例销毁之前调用
			sessionStorage.removeItem('chatContent')
		},
		beforeRouteLeave(to, from, next) {
			// 导航离开当前组件的对应路由调用
			sessionStorage.removeItem('chatContent')
			next()
		}
	};
</script>

<style scoped="scoped">
	.pageTitle {
		padding: 10px 20px;
		border-bottom: 1px solid #DCDCDC;
		height: 60px;
		align-items: center;
		font-size: 16px;
	}

	.pageContent {
		padding: 20px;
	}

	.messageBox {
		border: 1px solid #DCDCDC;
		height: 700px;
	}

	.webSoketBox {
		width: 580px;
		overflow: hidden;
	}

	.webSoketBoxHeader {
		width: 100%;
		border-bottom: 1px solid #DCDCDC;
		height: 60px;
		line-height: 60px;
		padding: 0 12px;
		background: #F9F9F9;
		box-shadow: 0 -2px 8px 1px rgba(0, 0, 0, 0.2);
		position: relative;
		z-index: 9;
	}

	.webSoketMessage {
		width: 580px;
		height: 378px;
		background: #F9F9F9;
		overflow: hidden;
		/* padding: 20px 10px; */
	}

	.webSoketInputBox {
		height: 260px;
		padding: 10px;
	}

	.webSoketBoxIcon {
		height: 40px;
		padding: 10px 0;
		justify-content: space-between;
		flex-wrap: nowrap;
	}

	.webSoketBoxIcon span {
		color: #C9C9C9;
		cursor: pointer;
	}

	.funcImageBox {
		justify-content: flex-start;
		cursor: pointer;
	}

	.webSoketBoxinput {
		width: 100%;
		height: 158px;
		padding: 10px 0;
		outline: none;
		overflow-y: auto;
		resize: none;
		border: none;
	}

	.webSoketBoxBtn {
		padding-top: 10px;
		text-align: right;
	}

	.receiveBox .webSoketHeadImg {
		width: 40px;
		height: 40px;
		border-radius: 5px;
		margin-right: 10px;
	}

	.receiveBox {
		justify-content: flex-start;
	}

	.receiveBoxName {
		color: #AAAAAA;
		font-size: 12px;
		margin-bottom: 5px;
	}

	.receiveBoxCont,
	.sendBoxCont {
		max-width: 300px;
		background: #FFFFFF;
		padding: 10px;
		color: #333333;
		font-size: 12px;
		border: 1px solid #DCDCDC;
		position: relative;
		text-align: justify;
		z-index: 5;
		border-radius: 5px;
		word-break: break-all;
	}

	.receiveBoxCont::before,
	.receiveBoxCont::after,
	.sendBoxCont::before,
	.sendBoxCont::after {
		content: '';
		position: absolute;
		width: 6px;
		height: 6px;
		border: 1px solid #DCDCDC;
		background: #FFFFFF;
		transform: rotate(45deg);
		border-radius: 1px;
	}

	.receiveBoxCont::before {
		left: -5px;
		top: 10px;
		z-index: 4;
	}

	.receiveBoxCont::after {
		border: 1px solid #FFFFFF;
		left: -2px;
		top: 10px;
		z-index: 6;
	}

	.sendBox {
		justify-content: flex-end;
	}

	.sendBox .webSoketHeadImg {
		width: 40px;
		height: 40px;
		border-radius: 5px;
		margin-left: 10px;
	}

	.sendBox .receiveBoxName {
		text-align: right;
	}

	.sendBox .sendBoxCont::before {
		right: -5px !important;
		top: 10px;
		z-index: 4;
	}

	.sendBox .sendBoxCont::after {
		border: 1px solid #FFFFFF;
		right: -2px !important;
		top: 10px;
		z-index: 6;
	}

	.webSoketUl {
		padding: 20px 10px;
		position: relative;
	}
	.iconLadingBox{
		/* position: absolute; */
		width: 50%;
		margin-left: 25%;
		height: 30px;
		text-align: center;
		top: 10px;
		font-size: 18px;
		transition: all .2s;
	}
	.webSoketUl,
	.webSoketUl li {
		width: 100%;
	}

	.webSoketUl li {
		margin-bottom: 20px;
	}

	.webSokeTip {
		width: 100%;
		text-align: center;
		font-size: 12px;
		color: #AAAAAA;
	}

	.funcImage {
		width: 20px;
		height: 20px;
		margin-right: 15px;
	}
</style>
